import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:provider/provider.dart';
import '../core/theme_config.dart';
import '../components/nba_video_player.dart';

class LivePage extends StatefulWidget {
  const LivePage({Key? key}) : super(key: key);

  @override
  State<LivePage> createState() => _LivePageState();
}

class TvChannel {
  final String name;
  final String url;
  const TvChannel(this.name, this.url);
}

class TvChannelGroup {
  final String name;
  final List<TvChannel> channels;
  const TvChannelGroup(this.name, this.channels);
}

class _LivePageState extends State<LivePage> {
  // 频道分组与当前选择
  List<TvChannelGroup> _groups = [];
  int _currentGroupIndex = 0;
  TvChannel? _currentChannel;
  bool _isLoading = false;
  Key _playerKey = UniqueKey();

  @override
  void initState() {
    super.initState();
    _loadChannels();
  }

  Future<void> _loadChannels() async {
    setState(() {
      _isLoading = true;
    });
    
    try {
      // 首先尝试加载online.m3u8文件
      final m3u8Content = await rootBundle.loadString('assets/online.m3u8');
      final m3u8Groups = _parseM3U8Content(m3u8Content);
      
      if (m3u8Groups.isNotEmpty) {
        setState(() {
          _groups = m3u8Groups;
          _currentGroupIndex = 0;
          _currentChannel = _groups.first.channels.first;
          _isLoading = false;
        });
        return;
      }
    } catch (e) {
      print('解析online.m3u8文件失败: $e');
    }
  }

  /// 解析M3U8文件内容
  List<TvChannelGroup> _parseM3U8Content(String content) {
    final lines = content.split('\n');
    final groups = <TvChannelGroup>[];
    final groupMap = <String, List<TvChannel>>{};
    
    String? currentGroupTitle;
    String? currentChannelName;
    
    for (final line in lines) {
      final trimmedLine = line.trim();
      if (trimmedLine.isEmpty) continue;
      
      if (trimmedLine.startsWith('#EXTINF:')) {
        // 解析频道信息行
        final groupMatch = RegExp(r'group-title="([^"]+)"').firstMatch(trimmedLine);
        final nameMatch = RegExp(r',(.+)$').firstMatch(trimmedLine);
        
        if (groupMatch != null) {
          currentGroupTitle = groupMatch.group(1);
        }
        if (nameMatch != null) {
          currentChannelName = nameMatch.group(1)?.trim();
        }
      } else if (!trimmedLine.startsWith('#') && currentChannelName != null) {
        // 这是URL行
        final url = trimmedLine;
        if (url.isNotEmpty && currentGroupTitle != null && currentChannelName != null) {
          if (!groupMap.containsKey(currentGroupTitle)) {
            groupMap[currentGroupTitle] = [];
          }
          groupMap[currentGroupTitle]!.add(TvChannel(currentChannelName, url));
        }
        
        // 重置当前频道信息
        currentChannelName = null;
      } else if (trimmedLine == '#EXTM3U') {
        // M3U文件头，忽略
        continue;
      }
    }
    
    // 将分组映射转换为TvChannelGroup列表
    return groupMap.entries.map((entry) {
      return TvChannelGroup(entry.key, entry.value);
    }).toList();
  }

  void _switchGroup(int index) {
    if (index == _currentGroupIndex) return;
    setState(() {
      _currentGroupIndex = index;
      _currentChannel = _groups[index].channels.first;
    });
  }

  void _playChannel(TvChannel channel) {
    setState(() {
      _currentChannel = channel;
      // 强制重新创建播放器组件，通过生成唯一key
      _playerKey = UniqueKey();
    });
  }

  @override
  Widget build(BuildContext context) {
    final theme = Provider.of<ThemeConfig>(context);
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: theme.currentGradient,
        ),
        child: SingleChildScrollView(
          padding: EdgeInsets.zero,
          physics: const AlwaysScrollableScrollPhysics(),
          child: Column(
          children: [
            // 加载状态显示
            if (_isLoading)
              const LinearProgressIndicator(),
            
            // 播放器区域
            if (_currentChannel != null)
              Padding(
                padding: const EdgeInsets.fromLTRB(12, 12, 12, 8),
                child: NbaVideoPlayer(
                  key: _playerKey, // 使用唯一key强制重新创建
                  vid: '',
                  title: _currentChannel!.name,
                  videoData: {
                    'm3u8_url': _currentChannel!.url,
                    'flv_url': _currentChannel!.url,
                    'image': '',
                  },
                  aspectRatio: 16 / 9,
                ),
              )
            else
              Padding(
                padding: const EdgeInsets.all(24),
                child: Text(
                  '暂无电视信号',
                  style: TextStyle(
                    color: theme.currentTextColor,
                    fontSize: 16,
                  ),
                ),
              ),

            // 分组切换
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
              child: Row(
                children: List.generate(_groups.length, (i) {
                  final selected = i == _currentGroupIndex;
                  return Padding(
                    padding: const EdgeInsets.only(right: 8),
                    child: ChoiceChip(
                      label: Text(_groups[i].name),
                      selected: selected,
                      onSelected: (_) => _switchGroup(i),
                    ),
                  );
                }),
              ),
            ),
            // 频道列表（随页面整体滚动）
            Container(
              padding: const EdgeInsets.fromLTRB(12, 8, 12, 12),
              child: GridView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  childAspectRatio: 3.5,
                  mainAxisSpacing: 8,
                  crossAxisSpacing: 8,
                ),
                itemCount: _groups.isEmpty ? 0 : _groups[_currentGroupIndex].channels.length,
                itemBuilder: (context, index) {
                  final ch = _groups[_currentGroupIndex].channels[index];
                  final isCurrent = _currentChannel?.name == ch.name;
                  return InkWell(
                    onTap: () => _playChannel(ch),
                    child: Container(
                      decoration: BoxDecoration(
                        color: isCurrent ? Colors.blue.shade50 : Colors.white,
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(color: isCurrent ? Colors.blue : Colors.grey.shade300),
                      ),
                      alignment: Alignment.center,
                      child: Text(
                        ch.name,
                        style: TextStyle(
                          color: isCurrent ? Colors.blue : theme.currentTextColor,
                          fontWeight: isCurrent ? FontWeight.bold : FontWeight.normal,
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
          ),
        ),
      ),
    );
  }
}
